#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : video_synthesis_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/22 09:40
"""
import json
import os.path
import traceback
from core.video.clip import *
from multiprocessing import Process

from worker.base_worker import BaseThread
from core.video.normal_synthesis import NormalVideoSynthesis
from core.video.auto_synthesis import AutoSynthesis
from utils.load_file import load_files
from log import log


def do_work(params, queue):
    log.debug(f"video_systhesis: {params}")
    channels = params.get("channels")
    video_groups = params.get("video_groups")
    num_outputs = params.get("num_outputs")
    import_subtitle = params.get("import_subtitle")
    subtitle_path = params.get("subtitle_path")
    keep_original_audio = params.get("keep_original_audio")
    auto_match_audio = params.get("auto_match_audio")
    audio_path = params.get("audio_path")
    audio_status = params.get("audio_status")
    total_duration = params.get("total_duration")
    speed = params.get("speed")
    output_dir = params.get("output_dir")
    video_priority = params.get("video_priority")
    resolution = eval(params.get("resolution"))
    set_title = params.get("set_title")
    set_background_music = params.get("set_background_music")
    set_overlay = params.get("set_overlay")
    set_cover = params.get("set_cover")
    set_watermark = params.get("set_watermark")
    set_filters = params.get("set_filters")
    kwargs = params.get("kwargs")
    if channels == "auto":
        func = AutoSynthesis(
            video_path=video_groups,
            num=params.get("num"),
            rule=params.get("rule"),
            times=params.get("times"),
            select_rule=params.get("select_rule", "random"),
            num_outputs=num_outputs,
            import_subtitle=import_subtitle,
            subtitle_path=subtitle_path,
            keep_original_audio=keep_original_audio,
            auto_match_audio=auto_match_audio,
            audio_path=audio_path,
            audio_status=audio_status,
            total_duration=total_duration,
            speed=speed,
            output_dir=output_dir,
            video_priority=video_priority,
            resolution=resolution,
            set_title=set_title,
            set_background_music=set_background_music,
            set_overlay=set_overlay,
            set_cover=set_cover,
            set_watermark=set_watermark,
            set_filters=set_filters,
            **kwargs)
    else:
        for v in video_groups:
            if isinstance(v.get("files"), str):
                if os.path.isdir(v.get("files")):
                    v["files"] = load_files(v.get("files"))
                elif os.path.isfile(v.get("files")):
                    v["files"] = [v.get("files")]
                else:
                    raise ValueError("文件路径错误")

            elif isinstance(v.get("files"), list):
                for f in v.get("files"):
                    if not os.path.isfile(f):
                        raise ValueError("文件路径错误")
            else:
                raise ValueError("文件错误")
        func = NormalVideoSynthesis(
            video_groups=video_groups,
            num_outputs=num_outputs,
            import_subtitle=import_subtitle,
            subtitle_path=subtitle_path,
            keep_original_audio=keep_original_audio,
            auto_match_audio=auto_match_audio,
            audio_path=audio_path,
            audio_status=audio_status,
            total_duration=total_duration,
            speed=speed,
            output_dir=output_dir,
            video_priority=video_priority,
            resolution=resolution,
            set_title=set_title,
            set_background_music=set_background_music,
            set_overlay=set_overlay,
            set_cover=set_cover,
            set_watermark=set_watermark,
            set_filters=set_filters,
            **kwargs
        )

    func.generate(queue)

    queue.put("done")


class VideoSynthesisWorker(BaseThread):
    """视频合成线程"""
    def __init__(self, params, parent=None):
        super(VideoSynthesisWorker, self).__init__(params, parent)
        self.params = params

    def run(self):
        try:
            self.process = Process(target=do_work, args=(self.params, self.queue))
            self.process.start()
            while True:
                msg = self.queue.get()
                if msg == "done":
                    break
                self.on_change_progress(msg)

        except Exception as e:
            traceback.print_exc()
            self.failed.emit(e)